package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.domain.Cabinet;
import com.share.device.domain.Station;
import com.share.device.domain.StationLocation;
import com.share.device.mapper.StationMapper;
import com.share.device.repository.StationLocationRepository;
import com.share.device.service.ICabinetService;
import com.share.device.service.IRegionService;
import com.share.device.service.IStationService;
import jakarta.annotation.Resource;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 站点服务实现类
 * @author zxl
 * @date 2025年03月20日 22:34
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements IStationService {
    @Resource
    ICabinetService cabinetService;

    @Resource
    IRegionService regionService;

    @Resource
    StationLocationRepository stationLocationRepository;

    @Override
    public List<Station> selectStationList(Station station) {
        List<Station> list = baseMapper.selectStationList(station);
        // 取出所有站点的柜机id
        List<Long> cabinetIdList = list.stream().map(Station::getCabinetId).toList();
        // 创建一个map，key是cabinetId，value是cabinetNo
        Map<Long,String> cabinetIdToCabinetNoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(cabinetIdList)) {
            List<Cabinet> cabinetList = cabinetService.list(new LambdaQueryWrapper<Cabinet>().in(Cabinet::getId, cabinetIdList));
            // 转换为cabinetId与cabinetNo的映射关系
            cabinetIdToCabinetNoMap = cabinetList.stream().collect(Collectors.toMap(Cabinet::getId, Cabinet::getCabinetNo));

        }
        for (Station item : list) {
            // 填充站点的柜机编号
            item.setCabinetNo(cabinetIdToCabinetNoMap.get(item.getCabinetId()));
        }
        return list;
    }

    /**
     * 新增站点
     * @param station
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveStation(Station station) {
        // 获取省市区名称
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        // 完整地址：省市区+详细地址
        station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
        int res = this.save(station) ? 1 : 0;
        // 同步站点位置信息到MongoDB
        StationLocation stationLocation = new StationLocation();
        // 设置站点id,由于是新添加的，所以使用mongodb的ObjectId来获取
        stationLocation.setId(ObjectId.get().toString());
        // 设置站点id
        stationLocation.setStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(
                station.getLongitude().doubleValue(),
                station.getLatitude().doubleValue()
                ));
        stationLocation.setCreateTime(new Date());
        // 向mongoDB中保存站点位置信息
        stationLocationRepository.save(stationLocation);
        return res;
    }

    /**
     * 修改站点
     * @param station
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateStation(Station station) {
        String provinceName = regionService.getNameByCode(station.getProvinceCode());
        String cityName = regionService.getNameByCode(station.getCityCode());
        String districtName = regionService.getNameByCode(station.getDistrictCode());
        station.setFullAddress(provinceName + cityName + districtName + station.getAddress());
        int res = this.updateById(station) ? 1 : 0;
        //同步站点位置信息到MongoDB
        StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(
                station.getLongitude().doubleValue(),
                station.getLatitude().doubleValue()
        ));
        stationLocationRepository.save(stationLocation);
        return res;
    }

    /**
     * 站点设置关联数据
     * 站点关联了柜机，柜机的状态就要设置为1使用中
     * @param station
     * @return
     */
    @Override
    public int setData(Station station) {
        this.updateById(station);

        //更正柜机使用状态
        Cabinet cabinet = cabinetService.getById(station.getCabinetId());
        cabinet.setStatus("1");
        cabinetService.updateById(cabinet);
        return 1;
    }

    @Override
    public void updateData() {
        //所有站点列表
        List<Station> stationList = list();
        for (Station station : stationList) {
            StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
            if (stationLocation == null) {
                // 如果mongodb中没有这个站点的位置信息，则创建一个
                stationLocation = new StationLocation();
                stationLocation.setId(ObjectId.get().toString());
                stationLocation.setStationId(station.getId());
                stationLocation.setLocation(new GeoJsonPoint(
                        station.getLongitude().doubleValue(),
                        station.getLatitude().doubleValue()));
                stationLocation.setCreateTime(new Date());
                // 保存到mongodb中,stationLocationRepository可以理解为就是mysql中的mapper
                stationLocationRepository.save(stationLocation);
            }
        }
    }

    /**
     * 重写批量删除方法，增加删除mongodb中的站点位置信息的删除逻辑
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        for (Object id : list) {
            stationLocationRepository.deleteByStationId(Long.parseLong(id.toString()));
        }
        return super.removeByIds(list);
    }
}
